function filenan = savecond(filena,ext,boxname)
%
%SAVECOND Conditioned saving options
%
%filenan = savecond(filena)
%
% If 'filena' is a string with extension '.mat', the function verifies 
% the existence of the file whose name is 'filena'.
% If 'filena' is a extensionless string, or has extension different from
% 'mat', the default extension '.mat' is added, i.e. the filename
% 'filena.mat' is used.
% The filename 'filena' can contain the file path.
% If the file already exists, three options are possible: 
%   1) overwriting; 
%   2) saving with another filename. A dialog box named 'FILENAME' appears;
%   3) no save. 
% In the third case, filena is empty.
%
%filenan = savecond(filena,ext)
%
% As above, but the extension 'ext' is considered. If 'filena' is
% extensionless, or its extension is different from 'ext', the 
% extension 'ext' is added. For example, is 'ext' is 'mat',
% 'filena.mat' is considered.
%
%filenan = savecond(filena,boxname)
%
% The string 'boxname', having at least three characters, in this
% case is considered as name of the dialog box if the option 2) appears.
%
%filenan = savecond(filena,ext,boxname)
%
% In this case, the two possibilities as above are combined.
%
% If 'filena' is not a valid filename, 'filenan' is empty.
%
% This function does not perform the data saving, which is instead 
% operated calling SAVE od DLMREAD. Simply, this function allow the
% management of data saving conditions.

% G. Teza, 2007.

if ~ischar(filena), filenan = []; return; end

if nargin == 2
    if length(ext) <= 3
        boxname = 'FILENAME';
    else
        boxname = ext; ext = '.mat';
    end
end
if nargin == 1, ext = '.mat'; boxname = 'FILENAME'; end

[fi,pa] = uiputfile(ext,boxname,filena);
if fi ~= 0
    filenan = fullfile(pa,fi);
else
    filenan = [];
end